import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Form, Input, Select, Button, Upload, Icon, Modal, Cascader, message
} from 'antd';

import { getCompanyVnvoiceInfo, getDistrictData, uploadUrl, updateCompanyInvoiceInfo } from "../../../services/api";
// import PFromUpload from "../../../components/Pro/PFromUpload";
const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;

/* const children = [];
 *//* const options = [{
value: 'zhejiang',
label: 'Zhejiang',
children: [{
value: 'hangzhou',
label: 'Hangzhou',
children: [{
value: 'xihu',
label: 'West Lake',
}],
}],
}, {
value: 'jiangsu',
label: 'Jiangsu',
children: [{
value: 'nanjing',
label: 'Nanjing',
children: [{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
}],
}],
}]; */
/* for (let i = 10; i < 36; i++) {
  children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
} */


@connect(state => ({
  profile: state.profile,
}))

@Form.create()

export default class Invoice extends Component {
  state = {
    loading:false,
    "telephone": "",
    "bankAccount": "",
    "bank": "建设银行",
    "province": '',
    "city": '',
    "area": '',
    "address": "",
    "taxRegCerNo": "",
    "taxPayerType": "",
    "taxRegCerUrl": "",
    "businessLicenseUrl": "",
    "generalTaxProveUrl": "",
    "authEntrustUrl": "",
    "bankAccountLicenseUrl": "",
    "comId": '',
    "comName": "",
    "comProvice": "",
    "comCity": "",
    "comArea": "",
    previewVisible: false,
    previewImage: '',
    options: [],
    taxRegCerUrlList: [{
      uid: -1,
      name: 'xxx.png',
      status: 'done',
      url: "/zj.png",
    }],
    businessLicenseUrlList: [{
      uid: -1,
      name: 'xxx.png',
      status: 'done',
      url: "/zj.png",
    }],
    generalTaxProveUrlList: [{
      uid: -1,
      name: 'xxx.png',
      status: 'done',
      url: "/zj.png",
    }],
    authEntrustUrlList: [{
      uid: -1,
      name: 'xxx.png',
      status: 'done',
      url: "/zj.png",
    }],
    bankAccountLicenseUrlList: [{
      uid: -1,
      name: 'xxx.png',
      status: 'done',
      url: "/zj.png",
    }],
  };

  componentDidMount() {

    /* (async () => {
      console.log('aaa');
      const data = await getDistrictData({}).catch((err) => { console.log(err); });
      console.log(data, 'async');
    })(); */

    getDistrictData({}).then((data1) => {
      console.log(data1, "getDistrictData");
      function generadata(data) {
        return data.map((val) => {
          const obj = {};
          obj.label = val.regionName;
          obj.value = val.regionId + "";
          if (val.childs && val.childs.length > 0) {
            obj.children = generadata(val.childs);
          }
          return obj;
        });
      }
      const options1 = generadata(data1.data);
      this.setState({ options: options1 });
      this.getCompanyVnvoiceInfoSd();
    }, (err) => {
      console.log(err, "getDistrictData");
    });
  }

  getCompanyVnvoiceInfoSd = () => {
    getCompanyVnvoiceInfo({}).then((data) => {
      console.log(data, "getCompanyVnvoiceInfo");
      this.setState({ ...data.data });
    }, (err) => {
      console.log(err, "getCompanyVnvoiceInfo");
    });
  };

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };

  beforeUpload = (file) => {
    const types = ["image/png", "image/jpeg", "image/jpg"];
    console.log(file.type);
    if (types.indexOf(file.type) === -1) {
      message.error('只能上传图片!');
      return false;
    }
    const isLt3M = file.size / 1024 / 1024 < 3;
    if (!isLt3M) {
      message.error('图片大小大于3MB!');
      return false;
    }

    return true;
    // return isJPG && isPNG && isLt3M;
  };

  handleChange = (info, field) => {
    console.log('infoinfo:' + info);
    console.log('123456',field);
    const { setFieldsValue } = this.props.form;
    let { fileList } = info;
    fileList = fileList.slice(-1);
    this.setState({ [field + "List"]: fileList });
    console.log(fileList, 'filist');
    //console.log(info,'info');
    console.log(info.file.status, 'info.file');
    if (info.file.status === 'removed') {
      message.error('至少需要一张图片');
      return;
    }
    if (info.file.status !== 'uploading') {
      console.log('info.file.response', info.file.response);
      if (info.file.response) {
        if (info.file.response.retType === "-1") {
          message.error(info.file.response.msg);
          return;
        }
      } else {
        return;
      }

      console.log(info.fileList, 'info.fileList');
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} 文件上传成功`);
      console.log(fileList, fileList.slice(-1), field, 'donefileListfield');

      this.setState({ [field + "List"]: fileList, [field]: fileList[0].response.data });
      setFieldsValue({ [field]: fileList.slice(-1) });

    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 文件上传失败.`);
    }
  };

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      console.log(values, "handleSubmit");

      if (!err) {
        /* this.props.dispatch({
          type: 'form/submitRegularForm',
          payload: values,
        }); */
        const data = { ...values, province: '' };
        [data.province, data.city, data.area] = values.provinceCityArea;
        if (data.city === undefined) {
          data.city = 0;
        }
        if (data.area === undefined) {
          data.area = 0;
        }
        // data.comId = this.state.comId;
        delete data.comProviceComCityComArea;
        delete data.comAddress;
        delete data.provinceCityArea;

        data.authEntrustUrl = this.state.authEntrustUrl;
        data.bankAccountLicenseUrl = this.state.bankAccountLicenseUrl;
        data.businessLicenseUrl = this.state.businessLicenseUrl;
        data.generalTaxProveUrl = this.state.generalTaxProveUrl;
        data.taxRegCerUrl = this.state.taxRegCerUrl;
        this.setState({loading: true});
        updateCompanyInvoiceInfo({...values}).then((data) =>{
          this.setState({loading: false});
        });
        // message.success('提交成功！');
      }
    });
  };
  callback = (key) => {
    console.log(key);
  };

  //验证电话
  checkTel = (rule, value, callback) => {
    if ((value && !(/^((0\d{2,3}-\d{7,8})|(1[0-9]{10}))$/).test(value)))  {
      callback('请输入正确的电话！');
    } else {
      callback();
    }
  };

  //验证公司银行账号,
  checkBank = (rule, value, callback) => {
    if (value && !(/^[0-9a-zA_Z]{16,}$/).test(value)) {
      callback('请输入正确的公司银行账号！');
    } else {
      callback();
    }
  };

  //验证税务登记证号码
  checkTaxRegCerNo = (rule, value, callback) => {
    if (value && !(/^[A-Za-z0-9]+$/).test(value)) {
      callback('请输入正确的税务登记证号码！');
    } else {
      callback();
    }
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { previewVisible, previewImage } = this.state;

    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    );

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const { state } = this;
    const uploadSorts = [
      { filelist: state.taxRegCerUrlList, filed: "taxRegCerUrl", action: uploadUrl, url: state.taxRegCerUrl, label: '税务登记证/统一信用代码证', msg: '请上传税务登记证/统一信用代码证', name: 'xfile' },
      { filelist: state.businessLicenseUrlList, filed: "businessLicenseUrl", action: uploadUrl, url: state.businessLicenseUrl, label: '营业执照副本', msg: '请上传营业执照副本', name: 'xfile' },
      { filelist: state.generalTaxProveUrlList, filed: "generalTaxProveUrl", action: uploadUrl, url: state.generalTaxProveUrl, label: '一般纳税人证明', msg: '请上传一般纳税人证明', name: 'xfile' },
      // { filelist: state.authEntrustUrlList, filed: "authEntrustUrl", action: uploadUrl, url: state.authEntrustUrl, label: '增值税授权委托书', msg: '请上传增值税授权委托书', name: 'xfile' },
      { filelist: state.bankAccountLicenseUrlList, filed: "bankAccountLicenseUrl", action: uploadUrl, url: state.bankAccountLicenseUrl, label: '银行开户许可证', msg: '请上传银行开户许可证', name: 'xfile' },
    ];
    const uploadSortsRender = () => {
      return uploadSorts.map((val) => {
        const item = val;
        item.filelist[0].url = val.url || "zj.png";

        return (<FormItem key={val.label}
          {...formItemLayout}
          label={val.label}
        >
          {getFieldDecorator(val.filed, {
            initialValue: item.filelist,
            rules: [{ required: true, message: val.msg }],
          })(
            <div>
              <Upload
                action={uploadUrl}
                listType="picture-card"
                fileList={item.filelist}
                name={val.name}
                onPreview={this.handlePreview}
                beforeUpload={this.beforeUpload}
                onChange={(obj) => {
                  this.handleChange(obj, val.filed);
                }}
                onRemove={() => {
                  return false;
                }}
              >
                {uploadButton}
              </Upload>
              <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                <img alt="example" style={{ width: '100%' }} src={previewImage} />
              </Modal>
            </div>
            )}
        </FormItem>);
      });
    };
    return (
    <div className="s_rtf s_erf">
      <Form
        onSubmit={this.handleSubmit}
        style={{ marginTop: 24 }}
      >
        <div className="card">基本信息</div>
        <FormItem
          {...formItemLayout}
          label="单位名称"
        >
          {getFieldDecorator('comName', {
            initialValue: state.comName,
            rules: [],
          })(
            <Input disabled placeholder="请输入" />
            )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="电话"
        >
          {getFieldDecorator('telephone', {
            initialValue: state.telephone,
            rules: [{
              required: true, message: '请输入电话！',
            }, {
              validator: this.checkTel
            }],
          })(
            <Input placeholder="请输入" maxLength="12" />
            )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="注册地址"
        >
          {getFieldDecorator('comProviceComCityComArea', {
            initialValue: [state.comProvice, state.comCity, state.comArea],
            rules: [{ required: true, message: '请选择国籍/地区' }],
          })(
            <Cascader disabled options={state.options} onChange={() => { }} />
            )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label=" "
          colon={false}
          className="detailedAddress"
        >
          {getFieldDecorator('comAddress', {
            initialValue: state.comAddress,
            rules: [{
              required: true, message: '请输入街道！',
            }],
          })(
            <TextArea disabled rows={3} placeholder="请填写公司注册详细地址" maxLength="100"/>
            )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="公司银行帐号"
        >
          {getFieldDecorator('bankAccount', {
            initialValue: state.bankAccount,
            rules: [{
              required: true, message: '请输入公司银行帐号！',
            }, {
              validator: this.checkBank
            }],
          })(
            <Input placeholder="请输入" maxLength="19" />
            )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="开户银行"
        >
          {getFieldDecorator('bank', {
            initialValue: state.bank,
            rules: [{
              required: true, message: '请输入开户银行！',
            }],
          })(
            <Input placeholder="请输入" maxLength="100" />
            )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="发票寄送地址"
        >
          {getFieldDecorator('provinceCityArea', {
            initialValue: [state.province + "", state.city + "", state.area + ""],
            rules: [{ required: true, message: '请选择国籍/地区' }],
          })(
            <Cascader options={this.state.options} onChange={() => { }} />
            )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label=" "
          colon={false}
          className="detailedAddress"
        >
          {getFieldDecorator('address', {
            initialValue: state.address,
            rules: [{
              required: true, message: '请输入街道！',
            }],
          })(
            <TextArea rows={3} placeholder="请输入街道" maxLength="100"/>
            )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="税务登记证号/统一信用代码证号"
        >
          {getFieldDecorator('taxRegCerNo', {
            initialValue: state.taxRegCerNo,
            rules: [{
              required: true, message: '请输入税务登记证号！',
            }, {
              validator: this.checkTaxRegCerNo
            }],
          })(
            <Input placeholder="请输入" maxLength="20" />
            )}
        </FormItem>
        <div className="card">证件扫描件</div>

        <FormItem
          {...formItemLayout}
          label="增值税纳税人类别"
        >
          {getFieldDecorator('taxPayerType', {
            initialValue: state.taxPayerType,
            rules: [{ required: true,message: '请选择增值税纳税人类别' }],
          })(
            <Select placeholder="请选择">
              <Option value="1">增值税一般纳税人</Option>
              <Option value="2">增值税小规模纳税人</Option>
            </Select>
            )}
        </FormItem>
        {uploadSortsRender()}
        {/*  <FormItem
          {...formItemLayout}
          label="税务登记证"
        >
          {getFieldDecorator('taxRegCerUrl', {
            rules: [{ required: true, message: '上传税务登记证' }],
          })(
            <Upload
              action={uploadUrl}
              listType="picture-card"
              fileList={[{
                uid: -1,
                name: 'xxx.png',
                status: 'done',
                url: state.taxRegCerUrl || "/zj.png",
              }]}
              onPreview={this.handlePreview}
              onChange={this.handleChange}
            >
              {uploadButton}
            </Upload>
            )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="营业执照副本"
        >
          {getFieldDecorator('businessLicenseUrl', {
            rules: [{ required: true, message: '请上传营业执照副本' }],
          })(
            <Upload
              action={uploadUrl}
              listType="picture-card"
              fileList={[{
                uid: -1,
                name: 'xxx.png',
                status: 'done',
                url: state.businessLicenseUrl || "/zj.png",
              }]}
              onPreview={this.handlePreview}
              onChange={this.handleChange}
            >
              {uploadButton}
            </Upload>
            )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="一般纳税人证明"
        >
          {getFieldDecorator('generalTaxProveUrl', {
            rules: [{ required: true, message: '请上传一般纳税人证明' }],
          })(
            <Upload
              action={uploadUrl}
              listType="picture-card"
              fileList={[{
                uid: -1,
                name: 'xxx.png',
                status: 'done',
                url: state.generalTaxProveUrl || "/zj.png",
              }]}
              onPreview={this.handlePreview}
              onChange={this.handleChange}
            >
              {uploadButton}
            </Upload>
            )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="增值税授权委托书"
        >
          {getFieldDecorator('authEntrustUrl', {
            rules: [{ required: true, message: '请上传增值税授权委托书' }],
          })(
            <Upload
              action={uploadUrl}
              listType="picture-card"
              fileList={[{
                uid: -1,
                name: 'xxx.png',
                status: 'done',
                url: state.authEntrustUrl || "/zj.png",
              }]}
              onPreview={this.handlePreview}
              onChange={this.handleChange}
            >
              {uploadButton}
            </Upload>
            )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="银行开户许可证"
        >
          {getFieldDecorator('bankAccountLicenseUrl', {
            rules: [{ required: true, message: '请上传银行开户许可证' }],
          })(
            <Upload
              action={uploadUrl}
              listType="picture-card"
              fileList={[{
                uid: -1,
                name: 'xxx.png',
                status: 'done',
                url: state.bankAccountLicenseUrl || "/zj.png",
              }]}
              onPreview={this.handlePreview}
              onChange={this.handleChange}
            >
              {uploadButton}
            </Upload>
            )}
        </FormItem> */}
        <FormItem
          {...formItemLayout}
          label=" "
          colon={false}
        >
          <Button size="large" type="primary" htmlType="submit" loading={this.state.loading}>
            提交
          </Button>
        </FormItem>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </Form>
    </div>
    );
  }
}
